﻿using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace RemoveCommentTool
{
    public partial class RemoveCommentTool : Form
    {
        private string sourceFolderPath = "";
        private string targetFolderPath = "";
        private bool isSelect2Convert = false;
        public RemoveCommentTool()
        {
            InitializeComponent();
        }
        private void clearListBox(ListBox lstBox)
        {
            if (null != lstBox)
            {
                lstBox.Items.Clear();
            }
        }
        private void addFile2Boxlist(string folderPath, ListBox lstBox)
        {
            if ("" != folderPath && lstBox != null)
            {
                DirectoryInfo fileSets = new DirectoryInfo(folderPath);
                foreach (FileInfo f in fileSets.GetFiles())
                {
                    //string fullName = f.FullName;
                    lstBox.Items.Add(f.Name);
                }
            }
        }
        private void btnSource_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "Please select the file directory";
            if (DialogResult.OK == dialog.ShowDialog())
            {
                this.sourceFolderPath = dialog.SelectedPath;
                textBoxSource.Text = dialog.SelectedPath;
                clearListBox(listBoxSource);
                clearListBox(listBoxTarget);
                addFile2Boxlist(this.sourceFolderPath, listBoxSource);
            }
        }

        private void textBoxSource_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void textBoxSource_DragDrop(object sender, DragEventArgs e)
        {
            string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            if (File.Exists(path))
            {
                path = System.IO.Path.GetDirectoryName(path);
            }
            this.sourceFolderPath = path;
            textBoxSource.Text = path;
            clearListBox(listBoxSource);
            clearListBox(listBoxTarget);
            addFile2Boxlist(this.sourceFolderPath, listBoxSource);
        }

        private void btnTarget_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "Please select the file directory";
            if (DialogResult.OK == dialog.ShowDialog())
            {
                this.targetFolderPath = dialog.SelectedPath;
                textBoxTarget.Text = dialog.SelectedPath;
            }
        }

        private void textBoxTarget_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void textBoxTarget_DragDrop(object sender, DragEventArgs e)
        {
            string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            if (File.Exists(path))
            {
                path = System.IO.Path.GetDirectoryName(path);
            }
            this.targetFolderPath = path;
            textBoxTarget.Text = path;
        }

        private void checkBoxSource_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chkBox = (CheckBox)sender;
            if (true == chkBox.Checked)
            {
                isSelect2Convert = true;
            }
            else
            {
                isSelect2Convert = false;
            }
        }

        private string readFile(string filePath, string encode)
        {
            string outputString = "";
            if (false == File.Exists(filePath))
            {
                return "";
            }
            try
            {
                using (FileStream fsSource = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    byte[] bytes = new byte[fsSource.Length];
                    int numBytesToRead = (int)fsSource.Length;
                    int numBytesRead = 0;
                    while (numBytesToRead > 0)
                    {
                        // Read may return anything from 0 to numBytesToRead.
                        int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
                        // Break when the end of the file is reached.
                        if (n == 0)
                            break;

                        numBytesRead += n;
                        numBytesToRead -= n;
                    }
                    numBytesToRead = bytes.Length;
                    Encoding ISO = Encoding.GetEncoding(encode);
                    outputString = ISO.GetString(bytes);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Throw a exception:" + ex.ToString());
                throw ex;
            }
            return outputString;
        }

        private bool writeFile(string path, string newFile, Encoding encoding)
        {
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (StreamWriter m_streamWriter = new StreamWriter(fs, encoding))
                    {
                        m_streamWriter.Flush();
                        //Set current file stream position
                        m_streamWriter.BaseStream.Seek(0, SeekOrigin.Begin);
                        //Write the content to file
                        m_streamWriter.Write(newFile);
                        //Close the file
                        m_streamWriter.Flush();
                        m_streamWriter.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Throw a exception:" + ex.ToString());
                throw ex;
            }
            return true;
        }
        private void btnConvert_Click(object sender, EventArgs e)
        {
            clearListBox(listBoxTarget);
            RemoveComment removeComment = new RemoveComment();
            if (isSelect2Convert == false)
            {
                foreach (string it in this.listBoxSource.Items)
                {
                    string saveFileName = "";
                    string saveFilePath = "";
                    CharDet detEncode = new CharDet();
                    string encode = detEncode.DetectCurrentFileEncode(sourceFolderPath + "\\" + it);
                    string outputFile = removeComment.removeProgramComment(readFile(sourceFolderPath + "\\" + it, encode));
                    if (targetFolderPath == "" || targetFolderPath == sourceFolderPath)
                    {
                        saveFileName = System.IO.Path.GetFileNameWithoutExtension(sourceFolderPath + "\\" + it) + "_bak" + System.IO.Path.GetExtension(sourceFolderPath + "\\" + it);
                        saveFilePath = sourceFolderPath + "\\" + saveFileName;
                    }
                    else
                    {
                        saveFileName = it;
                        saveFilePath = targetFolderPath + "\\" + saveFileName;
                    }
                    writeFile(saveFilePath, outputFile, Encoding.GetEncoding(encode));
                    listBoxTarget.Items.Add(saveFileName);
                }
            }
            else
            {
                foreach (string it in this.listBoxSource.SelectedItems)
                {
                    string saveFileName = "";
                    string saveFilePath = "";
                    CharDet detEncode = new CharDet();
                    string encode = detEncode.DetectCurrentFileEncode(sourceFolderPath + "\\" + it);
                    string outputFile = removeComment.removeProgramComment(readFile(sourceFolderPath + "\\" + it, encode));
                    if (targetFolderPath == "" || targetFolderPath == sourceFolderPath)
                    {
                        saveFileName = System.IO.Path.GetFileNameWithoutExtension(sourceFolderPath + "\\" + it) + "_bak" + System.IO.Path.GetExtension(sourceFolderPath + "\\" + it);
                        saveFilePath = sourceFolderPath + "\\" + saveFileName;
                    }
                    else
                    {
                        saveFileName = it;
                        saveFilePath = targetFolderPath + "\\" + saveFileName;
                    }
                    writeFile(saveFilePath, outputFile, Encoding.GetEncoding(encode));
                    listBoxTarget.Items.Add(saveFileName);
                }
            }
        }
    }
}
